<?php
// +----------------------------------------------------------------------
// | my
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2022 http://isofttime.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: $this <498944516@qq.com>
// +----------------------------------------------------------------------
namespace app\printer\model;

use think\Model;
use think\helper\Time;

class PrinterPic extends Model
{
    protected $insert = ['status'=>0];  
    protected $autoWriteTimestamp = true; 
    protected $status=['待打印','打印机中','打印成功'];
   
    public function info($key, $field = true)
    {
        
        if (!$key) return false;
        if (is_numeric($key)){
            $map['id'] = $key;
        }else{
            $map['openid'] = $key;
        }

        return $this->field($field)->where($map)->find();
    }

   

    // 保存消息记录
    public function checkPic($data,$printer)
    {
      
        $pic=getMedia($data['appid'],$data['MediaId']);
      
        $dirname="uploads/printer/".date('Ymd',time());
        createFolder($dirname); 
        

        $newpic_name= $data['openid']. md5(time().mt_rand(1,100)).".jpg";
        $info['url']=$dirname."/". $newpic_name;
        $fp = fopen($info['url'],'w');
        fwrite($fp, $pic); 
        fclose($fp);
        chmod($info['url'], 0777); 

      
        //零时处理水印大小，注意这里如果上传的图片权限不容许会报错
        if ($printer['qrcode'] !=''){
        $image = \think\Image::open($printer['qrcode']);
        $image->thumb(150,150,\think\Image::THUMB_CENTER)->save($printer['qrcode']);
        }
          
        
         //获取图片信息
        $image = \think\Image::open($info['url']);
        $info['width'] = $image->width(); 
        $info['height'] = $image->height(); 
        $info['type'] = $image->type();
        $info['style']=$info['width']>$info['height']?1:0;
    
        //处理文字水印
        switch ($info['style']) {
            case '1':
                $mytext=autoHang($printer['word_ad'],25);
                $y=-15;
                break;
            
            default:
                $mytext=autoHang($printer['word_ad'],17);
                $y=-15;
                break;
        }
     
        $thumb_size=$info['style']==1?array('1138','812'):array('812','1138');
        $image->thumb($thumb_size[0] ,$thumb_size[1],\think\Image::THUMB_CENTER);
         
        if ($printer['qrcode_ad']==1 and $printer['qrcode']) $image->water($printer['qrcode'],7);
        
        if ($printer['word_ad']!='' and $mytext) $image->text($mytext?$mytext['text']:'美丽和幸福将与你一路同行',  'HYQingKongTiJ.ttf', 24,'#ffffff',7,[170,-20]);
      
        if ($info['style']==1)  $image->rotate(); //旋转
        $image->save($info['url'],$info['type'],100);

      
        $info['aid']=$data['aid'];
        $info['appid']=$data['appid'];
        $info['shopid']=$printer['shopid'];
        $info['openid']=$data['openid'];
        $info['nickname']=$data['nickname'];
        $info['printer']=$printer['id'];
        $info['printer_title']=$printer['title'];
       
        $result =  $this->allowField(true)->save($info);
       
        return $info;
    }

    //正在打印的照片
     public function printtingTotal($ids)
    {
      
        // list($start, $end) = Time::today();
        $start=mktime(0, 0, 0, date('m'), date('d'), date('Y'));
        $map['create_time']=['EGT',$start];
        $map['status']=['in','0,1'];
        $map['printer']=['in',$ids];
        return $this->where($map)->count();

    }

     public function getUnsuccess($shopid)
    {
      
       $cur_date = strtotime(date('Y-m-d',time()));
       $map['shopid']=array('eq',$shopid);
       $map['status']=array('in','0,1');
       $map['create_time']=array('EGT',$cur_date);
       $pics=$this->where($map)->select();
     
       return $pics;

    }


     public function weList($data)
    {
      
       $user=model('admin/User')->info($data['userid'],'shopid');
       $map['shopid']=array('eq',$user['shopid']);
     
       $pics=db('PrinterPic')->where($map)->limit(10)->select();
       $message="打印列表（最后10条）";
       foreach ($pics as $key => $pic) {
          $message.="\n".$pic['id'].'：'.$pic['nickname'].'-'.$this->status[$pic['status']];
       }
       return ['message'=>$message];
     
    }

     public function again($data)
    {
        if (!is_numeric($data['back']))  return ['message'=>'照片编号必须是数字'];
        $res=db('PrinterPic')->where('id',$data['back'])->update(['status'=>0]);
        if ($res) return ['message'=>$data['back'].'号照片再次进入打印机'];
        return ['message'=>'再打失败'];
     
    }

      // 微信打印机
   public function addPic($data) {
       
       
       //检测打印服务是否正常
        $printer=model('printer/Printer')->checkPrinter($data['appid'],$data['openid']);
        if(!$printer)  return ['message'=>'没有识别到打印机，请扫描二维码后打印！'];

        $printer['qrcode']=get_cover($printer['qrcode'], 'path');

        //检查打印机是否在线
        if (!cache('printer_online_'.$printer['shopid'])) {
         
          //  $reply=[
          //   'template_id'=>'LsIc21raK3kWuX8j8hgBwJ-1cWn35PIdxgz2KMxgMPQ',
          //   'url'=>'http://baidu.com',
          //   'data'=>[
          //   'first'=>['value'=>'打印机监控未开启'],
          //   'keyword1'=>['value'=>'打印机监控未开启'],
          //   'remark'=>['value'=>'打印机监控未开启']
          //   ]
          //   ];
          // templateMessage($pic['openid'],$reply);
          $admins=model('we/WeFans')->getAdmins($data['appid']);
          foreach ($admins as $key => $admin) {
           $reply=['msgtype'=>'text','text'=>['content'=>$admin['nickname'].',你好，/:fade我检测到微信打印机监控未开启，顾客正在尝试打印，请及时检查']];
           send($admin['openid'],$reply,'customMessage');
          }
          
          return ['message'=>$printer['title']."监控没有开启，请联系你周围的客服人员"];
        } 

         //检查用户是否拥有资格,并且扣除本次消费
        $balance=model('printer/PrinterFans')->checkFans($data['openid'],$printer);
      
        if($balance<0) {
          return ['message'=>'余额不足，请充值后打印！'];
        }
    
        //检测照片是否合格,处理照片
        $info=$this->checkPic($data,$printer);
 
        // 计数
        model('printer/Printer')->addTotal($printer['id']);
       

        if ($info['width']<720 || $info['height']<720) $warn=',照片质量偏低，请下次打印高质量图片';

        
        $message="/:hug".$printer['title']."已经接收任务!";
        
        //查询排队情况
        $message.="\n/:hug前面有".$this->printtingTotal($printer['id'])."张照片正在在排队打印，耐心等待哦!";

        $message.="\n/:rose照片尺寸".$info['width'].'X'.$info['height'].(isset($warn)?$warn:'')."！";
        $message.="\n/:rose剩余打印次数".$balance;
        $message.="\n/:rose粉丝号".$data['fans']['id']."";
        return ['message'=>$message];
    }

   
}